package com.spring;

import com.spring.anno.Autowired;
import com.spring.anno.Component;
import com.spring.anno.ComponentScan;
import com.spring.anno.Scope;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyApplicationContext {
    private Class configClass;

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    public MyApplicationContext(Class configClass) {
        this.configClass = configClass;
        scan();
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if ("singleton".equals(beanDefinition.getScope())) {
              Object obj=  createBean(beanName,beanDefinition);
              singletonObjects.put(beanName,obj);
            }

        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();

        Object instance = null;
        try {

            instance = clazz.getConstructor().newInstance();

            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {

                    field.setAccessible(true);

                    field.set(instance, getBean(field.getName()));
                }
            }

            if (instance instanceof BeanNameAware) {
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            if (instance instanceof InitializingBean) {
                ((InitializingBean)instance).afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }


        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return instance;
    }

    public Object getBean(String beanName) {

        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new NullPointerException();
        }

        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

        if (beanDefinition.getScope().equals("singleton")) {
            Object singletonBean = singletonObjects.get(beanName);
            if (singletonBean == null) {
                singletonBean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        } else {
            // 原型
            Object prototypeBean = createBean(beanName, beanDefinition);
            return prototypeBean;
        }

    }

    /**
     * 扫描注解类，封装成BeanDefinition
     */
    private void scan() {
        if (!configClass.isAnnotationPresent(ComponentScan.class)) {
            return;
        }

        ComponentScan componentScanAnno = (ComponentScan)configClass.getAnnotation(ComponentScan.class);
        String scanPack = componentScanAnno.value();
        String path = scanPack.replace(".", "/");
        ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);

        File file = new File(resource.getFile());
        if (!file.isDirectory()) {
            return;
        }

        for (File f : file.listFiles()) {
            String absolutePath = f.getAbsolutePath();
            absolutePath = absolutePath.substring(absolutePath.indexOf("com/"), absolutePath.indexOf(".class"));
            String pack = absolutePath.replaceAll("/", ".");

            try {
                Class<?> aClass = classLoader.loadClass(pack);
                if (!aClass.isAnnotationPresent(Component.class)) {
                    return;
                }

                if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                    BeanPostProcessor instance = (BeanPostProcessor)aClass.getConstructor().newInstance();
                    beanPostProcessorList.add(instance);
                }

                Component component = aClass.getAnnotation(Component.class);
                String beanName = component.value();
                if ("".equals(beanName)) {
                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                }
                BeanDefinition beanDefinition = new BeanDefinition();
                beanDefinition.setType(aClass);

                if (aClass.isAnnotationPresent(Scope.class)) {
                    String scopeValue = aClass.getAnnotation(Scope.class).value();
                    beanDefinition.setScope(scopeValue);
                } else {
                    beanDefinition.setScope("singleton");
                }

                beanDefinitionMap.put(beanName, beanDefinition);

            } catch (ClassNotFoundException | NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}
